import React, { useState, useEffect, ReactNode } from 'react';
import { getLocale } from '@/locales';
import { ConfigProvider } from 'antd';
import enUS from 'antd/es/locale/en_US';
import zhCN from 'antd/es/locale/zh_CN';
import {ThemeType, LanguageType, SettingsContextType} from '@/types/settings';
import { SettingsContext } from './SettingsContext'; // 从新文件导入
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

const antdLocales = {
    en: enUS,
    zh: zhCN
};

interface SettingsProviderProps {
    children: ReactNode;
}

export const SettingsProvider: React.FC<SettingsProviderProps> = ({ children }) => {
    const [language, setLanguage] = useState<LanguageType>(
        (localStorage.getItem('app-language') as LanguageType) || 'zh'
    );
    const [theme, setTheme] = useState<ThemeType>(
        (localStorage.getItem('app-theme') as ThemeType) || 'light'
    );
    const [fontSize, setFontSize] = useState<number>(
        parseInt(localStorage.getItem('app-fontSize') || '14')
    );

    const locale = getLocale(language);
    dayjs.locale(language);
    const antdLocale = antdLocales[language] || zhCN;

    useEffect(() => {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('app-theme', theme);
    }, [theme]);

    useEffect(() => {
        localStorage.setItem('app-language', language);
    }, [language]);

    useEffect(() => {
        document.documentElement.style.setProperty('--font-size-base', `${fontSize}px`);
        localStorage.setItem('app-fontSize', fontSize.toString());
    }, [fontSize]);

    const changeLanguage = (lang: LanguageType) => {
        setLanguage(lang);
        dayjs.locale(lang);
    };

    const changeTheme = (newTheme: ThemeType) => {
        setTheme(newTheme);
    };

    const changeFontSize = (size: number) => {
        setFontSize(size);
    };

    const contextValue: SettingsContextType = {
        language,
        theme,
        fontSize,
        locale,
        changeLanguage,
        changeTheme,
        changeFontSize
    };

    return (
        <SettingsContext.Provider value={contextValue}>
            <ConfigProvider locale={antdLocale}>
                {children}
            </ConfigProvider>
        </SettingsContext.Provider>
    );
};